package com.tsing.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tsing.common.contants.JwtConstant;
import com.tsing.common.service.BaseRedisService;
import com.tsing.common.service.UserRedisService;
import com.tsing.common.vo.RolePerVo;
import com.tsing.common.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UserRedisServiceImpl implements UserRedisService {

    @Autowired
    private BaseRedisService baseRedisService;

    /**
     * 登录用户相关数据失效时间
     */
    @Value("${shiro.data.expire:1800}")
    String expire;

    @Override
    public UserVo getUserByToken(String token) {
        String userStr = baseRedisService.getString(token);
        if (StringUtils.isBlank(userStr)) {
            return null;
        }
        UserVo userVo = JSONObject.parseObject(userStr, UserVo.class);
        if (userVo != null) {
            return userVo;
        }
        return null;
    }

    @Override
    public List<String> getPermission(String role) {
        return baseRedisService.getListAll("permission" + role);
    }

    @Override
    public void saveUser2Redis(UserVo userVo) {
        baseRedisService.set(userVo.getToken(), JSONObject.toJSONString(userVo), userVo.getExpire());
    }

    @Override
    public void saveUserToken2Redis(UserVo userVo) {
        if (userVo.getExpire() > 0L) {
            baseRedisService.set(JwtConstant.USER_TOKEN + userVo.getId(), userVo.getToken(), userVo.getExpire());
        } else {
            baseRedisService.set(JwtConstant.USER_TOKEN + userVo.getId(), userVo.getToken(), Long.parseLong(expire));
        }
    }

    @Override
    public void savePermission2Redis(List<RolePerVo> list) {
        baseRedisService.delByKeyLike("permission");
        Map<String, List<RolePerVo>> collect = list.stream().collect(Collectors.groupingBy(RolePerVo::getRole));
        collect.forEach((key, value) -> {
            List<String> urls = value.stream().map(RolePerVo::getPermission).collect(Collectors.toList());
            baseRedisService.addList("permission" + key, urls);
        });
    }

}
